import { ref, reactive } from 'vue'
import { showMessage, toast } from '~/composables/util'
import { logout, updatepassword } from '~/api/manager'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

export function useRepassword() {
    const router = useRouter()
    const store = useStore()

    const formDrawerRef = ref(null)
    
    // 获取表单信息
    const form = reactive({
        oldpassword: "",
        password: "",
        repassword: ""

    })

    // 校验规则
    const rules = {
        oldpassword: [{ required: true, message: "旧密码不能为空", trigger: "blur" }],
        password: [{ required: true, message: "新密码不能为空", trigger: "blur" }],
        repassword: [{ required: true, message: "确认密码不能为空", trigger: "blur" }],
    }
    const formRef = ref(null);
    // 登入按钮状态 默认false

    const onSubmit = () => {
        formRef.value.validate((valid) => {
            if (!valid) {
                console.log("表单校验失败");
                return false;
            }
            formDrawerRef.value.showLoading()
            // 登入
            updatepassword(form).then(res => {
                toast("修改密码成功,请重新登录", "success", 2000);
                // 清楚用户状态
                store.dispatch("logout")
                // 跳转回登录页
                router.push("/login")
            })
                .finally(() => {
                    formDrawerRef.value.hideLoading()
                });
        });
    }

    const openRePasswordForm = () =>  formDrawerRef.value.open()

    return {
        formDrawerRef,
        form,
        rules,
        formRef,
        onSubmit,
        openRePasswordForm
    }
}

export function useLogout() {
    // 退出登录
    const router = useRouter()
    const store = useStore()
    function handleLogout() {
        showMessage("是否要退出登录？")
            .then(res => {
                // 不用接收api返回的成功或失败的信息 直接退出
                logout()
                    .finally(() => {
                        // 清楚用户状态
                        store.dispatch("logout")
                        // 跳转回登录页
                        router.push("/login")
                        // 提示退出登录成功
                        toast("退出登录成功")
                    })
            })
            .catch(err => {
            })
    }
    return {
        handleLogout
    }
}